package com.pangu.web.service.impl;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import com.pangu.core.BMDataContext;
import com.pangu.core.cache.CacheHelper;
import com.pangu.core.engine.game.ActionTaskUtils;
import com.pangu.util.disruptor.DisruptorHandler;
import com.pangu.web.model.Broadcast;
import com.pangu.web.model.PlayUser;
import com.pangu.web.model.PlayUserClient;
import com.pangu.web.service.repository.es.BroadcastESRepository;
import com.pangu.web.service.repository.es.PlayUserESRepository;
import com.pangu.web.service.repository.jpa.BroadcastRepository;

/**
 * 
 * Description:系统广播业务类
 *
 * @author abo
 * @date 2018年4月12日
 */
@Service
public class BroadcastServiceImpl {

	/**
	 * 
	 * Description: 保存并推送广播
	 * 
	 * @author abo
	 * @date 2018年4月12日
	 * @param playUserClient
	 *            赢钱用户
	 * @param goldCoins
	 *            赢钱金额
	 * @param gameType
	 *            游戏类型
	 */
	public void saveAndSendSocketBroadcast(PlayUserClient playUserClient, double goldCoins, String gameType) {
		// 封装广播对象
		Broadcast broadcast = new Broadcast();
		broadcast.setGametype(gameType);
		broadcast.setGoldcoins(goldCoins);
		broadcast.setCreatetime(new Date());
		broadcast.setUsername(playUserClient.getUsername());
		// 持久化用户数据
		DisruptorHandler.published(broadcast, BMDataContext.getContext().getBean(BroadcastESRepository.class),
				BMDataContext.getContext().getBean(BroadcastRepository.class));

		// 从上下文获取缓存对象
		// PlayUserESRepository playersRes =
		// BMDataContext.getContext().getBean(PlayUserESRepository.class);
		// // 从缓存里面查询在线人数
		// Page<PlayUser> list =
		// playersRes.findByOrgiAndOnline(playUserClient.getOrgi(), true, new
		// PageRequest(0, 999));
		Collection c = CacheHelper.getApiUserCacheBean().getAllCacheObject(BMDataContext.SYSTEM_ORGI);
		List<PlayUserClient> playUserClients = new ArrayList<PlayUserClient>();
		for (Object userId : c) {
			PlayUserClient puc = new PlayUserClient();
			puc.setId(userId.toString());
			playUserClients.add(puc);
		}
		// for (PlayUser playUser : list) {
		// PlayUserClient puc = new PlayUserClient();
		// puc.setId(playUser.getId());
		// lists.add(puc);
		// }
		// 发送socket请求给前端
		ActionTaskUtils.sendEvent(BMDataContext.BEIMI_PUSHBROADCAST_EVENT, broadcast, playUserClients);
	}
}
